<script setup>
import { ref } from 'vue'
import { addCarService, updateCarService } from '@/api/car.js'

// 控制抽屉的显示与隐藏
const visibleDrawer = ref(false)

const defaultDTO = {
  memberId: null, // 会员id
  plateNumber: null, // 车牌号
  brand: null, // 车辆品牌
  model: null // 车辆型号
}

const carDTO = ref({ ...defaultDTO })

// 向外暴露方法
const open = (row) => {
  visibleDrawer.value = true // 打开抽屉
  if (row.id) {
    const { id, memberId, plateNumber, brand, model } = row
    carDTO.value = { id, memberId, plateNumber, brand, model }
  } else {
    carDTO.value = { ...defaultDTO }
  }
}

// 提交逻辑
const emit = defineEmits(['success'])
const handleSubmit = async () => {
  if (carDTO.value.id) {
    await updateCarService(carDTO.value)
    ElNotification({
      title: '修改成功',
      type: 'success'
    })
    visibleDrawer.value = false
  } else {
    await addCarService(carDTO.value)
    ElNotification({
      title: '新增成功',
      type: 'success'
    })
    visibleDrawer.value = false
  }
  emit('success')
}

// 取消逻辑
const handleCancel = () => {
  visibleDrawer.value = false
  carDTO.value = { ...defaultDTO }
}

// 点击选择会员
const memberSelectRef = ref()
const handleSelectMember = () => {
  memberSelectRef.value.open()
}
// 处理新增选择的会员
const handleAddSelectedMember = (member) => {
  carDTO.value.memberId = member.id
}

defineExpose({
  open
})
</script>

<template>
  <el-drawer v-model="visibleDrawer" :title="carDTO.id ? '修改车辆信息' : '新增车辆'">
    <el-form :model="carDTO" ref="formRef" label-width="auto">
      <el-form-item label="会员ID" prop="memberId">
        <el-tag v-if="carDTO.memberId" type="primary" size="large" style="width: 50px"
          >{{ carDTO.memberId }}
        </el-tag>
        <el-button v-else type="primary" plain @click="handleSelectMember">选择会员</el-button>
        <el-button
          v-show="carDTO.memberId"
          type="danger"
          plain
          style="margin-left: 20px"
          @click="carDTO.memberId = null"
          >重新选择
        </el-button>
      </el-form-item>
      <el-form-item label="车牌号" prop="plateNumber">
        <el-input v-model="carDTO.plateNumber" placeholder="请输入车牌号"></el-input>
      </el-form-item>
      <el-form-item label="车辆品牌" prop="brand">
        <el-input v-model="carDTO.brand" placeholder="请输入车辆品牌"></el-input>
      </el-form-item>
      <el-form-item label="车辆型号" prop="model">
        <el-input v-model="carDTO.model" placeholder="请输入车辆型号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="handleSubmit">提交</el-button>
        <el-button type="info" plain @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
  <MemberSelect ref="memberSelectRef" @add="handleAddSelectedMember"></MemberSelect>
</template>
